import datetime

from django.contrib.auth.hashers import make_password
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import SysUser


# Create your views here.
# 注册用户信息视图类
class RegisterView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        """
        用户注册
        :param request:
        :return:
        """
        username = request.data.get('username')  # 获取用户名
        password = request.data.get('password')  # 获取密码
        email = request.data.get('email', '')  # 获取邮箱
        phonenumber = request.data.get('phonenumber', '')  # 获取手机号
        print(username, password, email, phonenumber)
        if not username or not password:
            return Response({
                'code': 400,
                'message': '⽤户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)
        # 检查⽤户名是否已存在
        if SysUser.objects.filter(username=username).exists():
            return Response({
                'code': 400,
                'message': '⽤户名已存在'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 写入数据到MySQL库
        try:
            user = SysUser.objects.create(
                username=username,  # 用户名
                password=make_password(password),  # 密码
                email=email,  # 邮箱
                phonenumber=phonenumber,  # 手机号
                status=0,  # 默认正常状态
                create_time=datetime.datetime.now(),  # 创建时间
                update_time=datetime.datetime.now()  # 更新时间
            )

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'注册失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response({
            'code': 200,
            'message': '注册成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        })
